#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# import os
from lxml import etree
import logging
import traceback
import json


def analyze_area(file_name, config):
    try:
        selector = etree.HTML(open(file_name, encoding='utf-8').read())
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    task_file = config.task_file
    try:
        check_id = selector.xpath('//section[@id="searchlist"]/a/@href')
        if len(check_id) > 0:
            companys = selector.xpath('//section[@id="searchlist"]/a/@href')
            with open(task_file, 'a', encoding='utf-8') as fp:
                for company in companys:
                    task_id = company[6:-5]
                    fp.write(task_id + '\n')
        else:
            # os.remove(file_name)
            logging.warning('invalid file {0}'.format(file_name))
            return -1
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_search(file_name, config):
    try:
        selector = etree.HTML(open(file_name, encoding='utf-8').read())
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    task_file = config.task_file
    try:
        check_id = selector.xpath('//span[@class="text-danger"]')
        if len(check_id) > 0:
            companys = selector.xpath('//table[@class="m_srchList"]/tbody/tr/td[2]/a/@href')
            with open(task_file, 'a', encoding='utf-8') as fp:
                for company in companys:
                    task_id = company[6:-5]
                    fp.write(task_id + '\n')
        else:
            # os.remove(file_name)
            logging.warning('invalid file {0}'.format(file_name))
            return -1
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_file_name(file_name, config):
    try:
        selector = etree.HTML(open(file_name, encoding='utf-8').read())
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    task_file = config.task_file
    try:
        companys = selector.xpath('string(//table[@class="m_srchList"]/tbody/tr/td[2]/a)')
        if len(companys) > 0:
            with open(task_file, 'a', encoding='utf-8') as fp:
                for company in companys:
                    name = company.xpath('string()')
                    firm_id = company.xpath('./@href')
                    task_id = firm_id[6:-5]
                    infos = file_name.split('/')
                    info = infos[-1]
                    word = info[:-5]
                    msg = '{0}\t{1}\t{2}\n'.format(word, task_id, name)
                    fp.write(msg)
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_multi_search(file_name, config):
    try:
        selector = etree.HTML(open(file_name, encoding='utf-8').read())
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    task_file = config.task_file
    try:
        companys = selector.xpath('//table[@class="m_srchList"]/tbody/tr/td[2]/a/@href')
        if len(companys) > 0:
            fp = open(task_file, 'a', encoding='utf-8')
            for company in companys:
                task_id = company[6:-5]
                fp.write(task_id + '\n')
            fp.close()
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_company(file_name, config):
    try:
        rds = config.rds
        queue = config.task_file
        html_file = file_name.split('/')[-1]
        url = 'http://www.qichacha.com/firm_{0}'.format(html_file[:-5])
        task = {'type': queue, 'url': url, 'file': file_name}
        rds.rpush(queue, json.dumps(task))
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_run(file_name, config):
    try:
        rds = config.rds
        queue = config.task_file
        html_file = file_name.split('/')[-1]
        url = 'http://www.qichacha.com/crun_{0}'.format(html_file[:-5])
        task = {'type': queue, 'url': url, 'file': file_name}
        rds.rpush(queue, json.dumps(task))
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0


def analyze_assets(file_name, config):
    try:
        rds = config.rds
        queue = config.task_file
        html_file = file_name.split('/')[-1]
        url = 'http://www.qichacha.com/cassets_{0}'.format(html_file[:-5])
        task = {'type': queue, 'url': url, 'file': file_name}
        rds.rpush(queue, json.dumps(task))
    except Exception as e:
        logging.error(e)
        logging.error(traceback.format_exc())
        return -2
    return 0
